var over = 0;
var page_status = 0; //1:新增 2：编辑
var id = 0;

var thisPage = {
    first: 0,
    scrollTo_01: function () {
        $('#divH_12').scrollLeft($('#divD_12').scrollLeft());
        $('#divD_11').scrollTop($('#divD_12').scrollTop());
    },
    //得到角色数据
    GetEntityData: function () {
        var item = {};
        item['roleId'] = $("#RoleId").val();
        item['roleNo'] = $.trim($("#RoleNo").val());        // 角色编号
        item['roleName'] = $.trim($("#RoleName").val());    // 角色名称
        item['description'] = formatNullInputValue($.trim($("#Description").val()));  // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());

        return JSON.stringify(item);
    },
    // 初始化页面
    OnPageLoad: function () {
        if (parseInt(page_status) === 2) {
            thisPage.PageInit();
        } else {
            thisPage.DoInsert();
            $('#loading').hide();
        }
    },
    PageInit: function () {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/admin/role/fetchByKey.html",
            timeout: 30 * 1000,
            data: JSON.stringify(id),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            var item = data.roleEntity;
            $("#RoleId").val(item.roleId);
            $("#RoleNo").val(item.roleNo);
            $("#RoleName").val(item.roleName);
            $("#Description").val(item.description);

            $("#RoleNo").focus();

            // 显示明细数据
            linesHandler.BuildDataTable(data.memberList);
        }).fail(function (data) {
            $('#loading').hide();
            parent.ajaxError(data, 1);
        }).always(function () {
            if (parseInt(thisPage.first) === 0) {
                thisPage.first = 1;
            }
        });
    },
    // 得到明细数据列表信息
    fetchMemberByRoleKey: function () {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/admin/role/lines/fetchMemberByRoleKey.html",
            timeout: 30 * 1000,
            data: JSON.stringify($("#RoleId").val()),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            linesHandler.BuildDataTable(data);

            page_status = 2;      // 将状态由增加 -> 编辑
            $("#SlaveArea").show();
        }).fail(function (data) {
            parent.ajaxError(data, 1);
        }).always(function () {
        });
    },
    //保存数据
    Save: function () {
        //step 1、进行页面验证，失败则返回
        if (!$("#mainForm").valid())
            return;

        //step 2、执行处理
        $.ajax({
            type: "POST",
            url: parent.basePath + "/admin/role/save.html",
            timeout: 30 * 1000,
            data: thisPage.GetEntityData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                showLoadmask();
            }
        }).done(function (data) {
            if (data > 0) {
                if (parseInt(page_status) === 1) {
                    $("#RoleId").val(data);   // 设置刚才插入的记录ID
                    $("#SlaveArea").show();
                }
                ShowSuccessMessagePanel("保存成功。");
            }
        }).fail(function (data) {
            parent.ajaxError(data, 1);
        }).always(function ( ) {
            hideLoadmask();
        });
    },
    // 新增
    DoInsert: function () {
        $('#RoleId').val("0");
        // 清空表单内容，准备下一个记录
        $(':input', '#mainForm').not(':button, :submit, :reset, :hidden')
                .val('').removeAttr('checked').removeAttr('selected');
        $('#mainForm')[0].reset();
        $("#mainForm").validate().resetForm();
        $("div.error").remove();
        $("img.errMsgTooltip").remove();
        $('#mainForm span.selectSpan').html('');

        $('#tabData01 tbody').empty();
        $("#SlaveArea").hide();
        linesHandler._rows = 0;
        //自适应高度
        setSlaveTableHeight();

        $("#RoleNo").focus();
        page_status = 1;
    }
};

//-----------------------------------------------------------------------------
// 明细处理部分
//-----------------------------------------------------------------------------
var linesHandler = {
    _rows: 0, // 共有多少行记录

    BuildDataTable: function (result) {
        $('#tabData01 tbody').empty();

        // 得到数据列表
        if (result === null) {
            $('#loading').hide();
            linesHandler._rows = 0;
            return false;
        }
        var content01 = '';
        linesHandler._rows = result.length;
        for (var i = 0; i < result.length; i++) {
            var id = result[i].userName;
            var sequence = i + 1;
            content01 += '<tr _mash_id="' + id + '">';
            content01 += '<td class="rowNumber">' + sequence + '</td>';
            content01 += '<td><span title="删除" class="trash" onclick="linesHandler.DoDelete(\'' + id + '\');"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            if (i > 0) {
                if (result[i].departmentName === result[i - 1].departmentName) {
                    content01 += '<td style="border-bottom:none;"></td>';
                } else {
                    content01 += '<td style="border-top:1px solid #c6c3bd; border-bottom:none;">' + formatNullData(result[i].departmentName) + '</td>';
                }
            } else {
                content01 += '<td style="border-bottom:none;">' + formatNullData(result[i].departmentName) + '</td>';
            }
            content01 += '<td>' + formatNullData(result[i].employeeName) + '</td>';
            content01 += '</tr>';

            $('#tabData01 tbody').append(content01);
            content01 = '';
        }

        $("#tabData01 tbody tr:odd").removeClass().addClass("odd");
        $("#tabData01 tbody tr:even").removeClass().addClass("even");

        setOneTableColor("tabData01");

        // 设置最后一行的样式
        var $lastLine = $('#tabData01 tbody tr:last-child');
        $lastLine.find('td').removeClass('last').addClass('last');

        //自适应高度
        setSlaveTableHeight();

        $('#loading').hide();
    },
    // 删除
    DoDelete: function (id) {
        curr_id = id;
        parent.showModal(333, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？', linesHandler.OnDelete);
    },
    //删除操作
    OnDelete: function () {
        var item = {};
        item['userName'] = curr_id;
        item['roleId'] = $("#RoleId").val();

        $.ajax({
            type: "POST",
            url: parent.basePath + "/admin/role/lines/delete.html",
            timeout: 30 * 1000,
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            if (data > 0) {
                thisPage.fetchMemberByRoleKey();
            }
        }).fail(function (data) {
            parent.ajaxError(data, 1);
        }).always(function ( ) {
        });
    },
    //增加明细
    AddLines: function () {
        parent.showModal(1095, 538, '选择系统用户', parent.basePath + '/popup/admin/membership/choice.html?flag=1', null, linesHandler.OnAddLines);
    },
    jsonresult: [],
    OnAddLines: function ($dialog) {
        var _exist = $.inArray($dialog, parent.arrDialog);
        if (_exist >= 0) {
            parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
        }
        //做列表选择设置
        if (parent.choice_success) {
            for (var i = 0; i < parent.arrChoice[0].length; i++) {
                var item = {};
                item['roleId'] = parseInt($("#RoleId").val());
                item['userName'] = parent.arrChoice[0][i].UserName;
                item['createdBy'] = parseInt($.trim($("#UserId").val()));
                item['updatedBy'] = parseInt($.trim($("#UserId").val()));

                linesHandler.jsonresult.push(item);
            }
            //清空数组
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
            //保存，根据所选成员用户，增加明细表记录
            linesHandler.DoAddUserIntoRole();
        }
    },
    // 新增明细记录
    DoAddUserIntoRole: function () {
        $.ajax({
            type: "POST",
            url: parent.basePath + '/admin/role/lines/insert.html',
            timeout: 30 * 1000,
            data: JSON.stringify(linesHandler.jsonresult),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                showLoadmask();
            }
        }).done(function (data) {
            // 刷新明细
            if (data > 0) {
                thisPage.fetchMemberByRoleKey();
            }
        }).fail(function (data) {
            parent.ajaxError(data, 1);
        }).always(function ( ) {
            //清空选择结果
            linesHandler.jsonresult.splice(0, linesHandler.jsonresult.length);
            hideLoadmask();
        });
    }
};

//-----------------------------------------------------------------------------
// 折叠处理
//-----------------------------------------------------------------------------

/* 展开 */
function expand() {
    $("#panelTop").show();
    $("#tb-field").show();
    $("#hPanelSplitter").children().removeClass("fa-angle-double-down").addClass("fa-angle-double-up");
    $("#hPanelSplitter").attr("title", "隐藏主表");
    $("#SlaveArea").css({top: 10});

    // 自适应高度
    setSlaveTableHeight();
}
/* 折叠 */
function collapse() {
    $("#panelTop").hide();
    $("#tb-field").hide();
    $("#hPanelSplitter").children().removeClass("fa-angle-double-up").addClass("fa-angle-double-down");
    $("#hPanelSplitter").attr("title", "显示主表");
    $("#SlaveArea").css({top: 5});

    // 自适应高度
    setSlaveTableHeight();
}

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    setWndTitle('角色编辑');
    setViewPosition('<span>系统管理</span>角色编辑');

    //从url得到相关参数
    page_status = jQuery.url.param("action");
    id = jQuery.url.param("id");

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            collapse();
        } else {
            expand();
        }
    });

    thisPage.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    var w = 1366;
    var h = $(window).height();

    $("#tb-field").css({width: w - 16, minWidth: 1350});
    $("#SlaveArea").css({left: 8, width: w - 16});
    $("#tabPanelContent").css({left: 0, width: w - 16});
    $("#SlaveDataArea_01").css({width: $("#SlaveArea").width()});
    $("#tabHeader01").css({width: $("#tabPanelContent").width() - 19});
    $("#tabData01").css({width: $("#tabPanelContent").width() - 19});

    // 自适应高度
    setSlaveTableHeight();

    //$("#tabHeader01").colResizable({contentTb: $("#tabData01"), pixDiffer: 1, draggingClass: null, liveDrag: true});

    over = 1;
}
// 根据窗口大小设置明细列表的高度（自适应高度）
function setSlaveTableHeight() {
    var h = $(window).height();
    var _tabTop = 298;   // 用于随着窗口变化，下面明细高度随之变化的一个节点

    if ($("#hPanelSplitter").children().hasClass("fa-angle-double-up"))
        _tabTop = 298;
    else
        _tabTop = 160;

    //$("#test").remove();
    //$(document.body).append('<div id="test" style="background:red;width:100%;position:absolute; top:' + _tabTop + 'px;display:block;height:5px;z-index:10000" />');
    var _rc = Math.floor((h - _tabTop - 50) / 24);
    var _dh = _rc * 24;
    var _rowH = linesHandler._rows * 24; // 计算行高
    _dh = (_rowH >= _dh) ? _dh : _rowH;

    $("#divD_11").css({"max-height": _dh - 1, height: _dh - 1});
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$(function () {
    $("#mainForm").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _RoleNo: "required",
            _RoleName: "required"
        },
        messages: {
            _RoleNo: "请填写角色编号。",
            _RoleName: "请填写角色名称。"

        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: showErrors  //使用自定义的错误显示方法
    });
});